﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Linq.Expressions;

namespace TinyPMS_Jerusalem.Models
{
    public class Repository<T> : Interface.IRepository<T> where T : class
    {
        private Type TTpye;
        protected DataContext context;

        public Repository(DataContext context)
        {
            this.context = context;
            TTpye = typeof(T);
        }

        public virtual void Add(T instance)
        {
            context.GetTable<T>().InsertOnSubmit(instance);
        }

        public virtual void Delete(T instance)
        {
            context.GetTable<T>().DeleteOnSubmit(instance);
        }

        public virtual void Save()
        {
            context.SubmitChanges();
        }

        public virtual T GetElementByID(string ID)
        {
            ParameterExpression expression_param = Expression.Parameter(TTpye, "p");
            BinaryExpression binaryExpression = Expression<Func<T, bool>>.Equal(Expression<Func<T, bool>>.Call(Expression<Func<T, bool>>.Property(expression_param, TTpye.GetProperty("ID")), TTpye.GetMethod("ToString")), Expression<Func<T, bool>>.Constant(ID));
            Expression<Func<T, bool>> expression = Expression<Func<T, bool>>.Lambda<Func<T, bool>>(binaryExpression, expression_param);
            IQueryable<T> result = GetAll().Where(expression);
            if (result.Count() == 0)
                return null;
            else
                return result.Single();
        }

        public virtual IEnumerable<T> GetAll(Func<T, bool> constrain)
        {
            return GetAll().Where(constrain);
        }

        public virtual IQueryable<T> GetAll()
        {
            return context.GetTable<T>();
        }

        public virtual bool IsExist(string ID)
        {
            ParameterExpression expression_param = Expression.Parameter(TTpye, "p");
            BinaryExpression binaryExpression = Expression<Func<T, bool>>.Equal(Expression<Func<T, bool>>.Call(Expression<Func<T, bool>>.Property(expression_param, TTpye.GetProperty("ID")), TTpye.GetMethod("ToString")), Expression<Func<T, bool>>.Constant(ID));
            Expression<Func<T, bool>> expression = Expression<Func<T, bool>>.Lambda<Func<T, bool>>(binaryExpression, expression_param);
            return GetAll().Where(expression).Count()>0;
        }
    }


}